package cai;

import java.io.File;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

public class Http_post {
	static Logger logger = Logger.getLogger(Http_post.class.getClass());
	HttpClient client = new HttpClient();

	/**
	 * 
	 * @param http
	 * @param userName
	 * @param password
	 * @throws Exception
	 */
	public String login(String http, NameValuePair userName,
			NameValuePair password) {
		PostMethod post = new PostMethod(http);
		post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
		post.setRequestBody(new NameValuePair[] { userName, password });
		int status;
		try {
			status = client.executeMethod(post);
			logger.info(status);
			logger.info(post.getResponseBodyAsString());
			return post.getResponseBodyAsString();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			post.releaseConnection();
		}
		return null;
	}

	/**
	 * 
	 * @param files
	 * @param postURL
	 */
	public String uploadFile(File[] files, String postURL) {
		MultipartPostMethod filePost = new MultipartPostMethod(postURL);
		filePost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8"); 
		try {
			client.setConnectionTimeout(8000);
			for (File f : files) {
				filePost.addParameter(f.getName(), f.getName(), f);
			}
			filePost.setRequestHeader("Content-type", "text/xml; charset=UTF-8");
			int s = client.executeMethod(filePost);
			logger.info(s);
			logger.info(filePost.getResponseBodyAsString());
			return filePost.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			filePost.releaseConnection();
		}
		return null;
	}

	public static void main(String args[]) throws Exception {
		Http_post h=new Http_post();
		NameValuePair userName=new NameValuePair("loginName","admin");
		NameValuePair password=new NameValuePair("pwd","adminynd");
		h.login("http://localhost:8080/ynd/AdminCheckLogin.do", userName, password);
		File[] files=new File[]{new File("C:\\ssq\\2011328_3D.jpg")};
		h.uploadFile(files, "http://localhost:8080/ynd/upload.do");
	}
}
